package com.glsc.ngateway.platform.service.it;

import com.glsc.ngateway.common.base.domain.mysql.gateway.platform.it.ItNetworkDevice;
import com.glsc.ngateway.common.base.domain.mysql.gateway.platform.User;
import com.glsc.ngateway.common.api.platform.dto.it.NetworkManageExportFull;
import com.glsc.ngateway.common.base.domainmapper.NetworkRowMapper;
import com.glsc.ngateway.common.base.repo.mysql.gateway.platform.it.ItNetworkDeviceRepo;
import com.glsc.ngateway.platform.service.UserService;
import com.glsc.ngateway.common.api.common.utils.DateUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Deprecated
@Service
public class NetworkService {

    Logger logger = LoggerFactory.getLogger(NetworkService.class);

    @Autowired
    private JdbcTemplate jdbcTemplate;

//    @Autowired
//    private GeneralDataManager generalDataManager;

    @Autowired
    private SequenceService sequenceService;

    @Autowired
    private UserService userService;

    @Autowired
    private ItNetworkDeviceRepo itNetworkDeviceRepo;

    public Page<ItNetworkDevice> queryAllSer(Integer page, Integer size, String userId) {
        Pageable pageable = PageRequest.of(page - 1, size);
        Page<ItNetworkDevice> list = itNetworkDeviceRepo.getNetworkDeviceByUser(pageable, userId);
        List<ItNetworkDevice> flist = list.getContent();
        try {
            for (ItNetworkDevice s : flist) {
                if (StringUtils.isNotEmpty(s.getUserId())) {
                    User user = userService.findByUserId(s.getUserId());
                    if (user != null) {
                        s.setDepartment(user.getUserDepartment());
                        s.setUserName(user.getName());
                    }
                }
            }
        } catch (Exception e) {
            logger.error("queryAllSer异常", e);
        }
        return list;
    }


    //    public String addNetwork(Map<String, Object> networkInfo) {
//        String networkId = "ZC-" + sequenceService.getNextValue("dev_network");
//        networkInfo.put("assetId", networkId);
//        Date currentTime = new Date();
//        networkInfo.put("insertTime", currentTime);
////		networkInfo.put("updateTime", currentTime);
//        // change the camel-naming to underline-naming
//        networkInfo = BeanUtil.camel2Underline(networkInfo);
//        generalDataManager.insert("t_network_device", networkInfo);
//        return networkId;
//    }
//
//    public void updateNetwork(Map<String, Object> networkInfo) {
//        Date currentTime = new Date();
//        networkInfo.put("insertTime", currentTime);
////		networkInfo.put("updateTime", currentTime);
//        // change the camel-naming to underline-naming
//        networkInfo = BeanUtil.camel2Underline(networkInfo);
//        generalDataManager.update("t_network_device", networkInfo, "asset_id");
//    }

    public void addOrUpdateNetwork(ItNetworkDevice itNetworkDevice, String userId) {
        if (StringUtils.isEmpty(itNetworkDevice.getAssetId())) {
            boolean con = true;
            String id = null;
            while (con) {
                String tmpid = "ZC-" + sequenceService.getNextValue("dev_network");
                logger.info("新增网络设备，生成唯一标识，临时" + tmpid);
                ItNetworkDevice i = itNetworkDeviceRepo.findByAssetId(tmpid);
                if (i == null) {
                    logger.info("新增网络设备，生成唯一标识，选中" + tmpid);
                    id = tmpid;
                    con = false;
                }
            }
            itNetworkDevice.setAssetId(id);
            itNetworkDevice.setUserId(userId);
        }
        itNetworkDeviceRepo.save(itNetworkDevice);
    }

    //删除网络设备
    public void deleteNetwork(String assetId) {
        ItNetworkDevice it = itNetworkDeviceRepo.findByAssetId(assetId);
        if (it != null) {
            itNetworkDeviceRepo.delete(it);
        }
    }

//    //搜索网络设备
//    public List<Map<String, Object>> searchNetwork(String nw, String user_id) {
//        //验证user_id的权限是否为admin
//        List<String> userRoles = userService.getUserAllRolesById(user_id);
//        boolean isAuth = false; //是否有权限新增
//        for (String role : userRoles) {
//            if ("admin".equals(role)) {
//                isAuth = true;
//                break;
//            }
//        }
//        String condition = "";
//        String sql = "";
//        if (isAuth) {
//            sql = "select a.*,b.department from t_network_device a left join t_admin_user b on a.user_id = b.user_id where 1 = 1 "
//                    + "and (asset_Ip like '%" + nw + "%' or brand_Sys like '%" + nw + "%' or brand_Sn like '%" + nw + "%') ";
//        } else {
//            condition += " and user_id = '" + user_id + "'";
//            condition += " order by insert_time desc ";
//            sql = "select a.*,b.department from t_network_device a left join t_admin_user b on a.user_id = b.user_id where 1 = 1 "
//                    + "and (asset_Ip like '%\"+nw+\"%' or brand_Sys like '%\"+nw+\"%' or brand_Sn like '%\"+nw+\"%') " + condition;
//        }
//        return BeanUtil.underline2Camel(jdbcTemplate.queryForList(sql));
//    }
//
//
//    //搜索网络设备名称
//    public List multiSearch(Map<String, Object> networkInfo) {
//        String condition = " where  1=1 ";
//        String assetIp = (String) networkInfo.get("assetIp");
//        if (!"".equals(assetIp) && assetIp != null) {
//            condition += " and asset_ip = '" + assetIp + "'";
//        }
//        Integer brand = (Integer) networkInfo.get("brand");
//        if (brand != null) {
//            condition += " and brand = " + brand.intValue();
//        }
//        String brandType = (String) networkInfo.get("brandType");
//        if (!"".equals(brandType) && brandType != null) {
//            condition += " and brand_type = '" + brandType + "'";
//        }
//        String brandSys = (String) networkInfo.get("brandSys");
//        if (!"".equals(brandSys) && brandSys != null) {
//            condition += " and brand_sys = '" + brandSys + "'";
//        }
//        String brandSn = (String) networkInfo.get("brandSn");
//        if (!"".equals(brandSn) && brandSn != null) {
//            condition += " and brand_sn = '" + brandSn + "'";
//        }
//        String capitalType = (String) networkInfo.get("capitalType");
//        if (!"".equals(capitalType) && capitalType != null) {
//            condition += " and capital_type = '" + capitalType + "'";
//        }
//        String capitalTyped = (String) networkInfo.get("capitalTyped");
//        if (!"".equals(capitalTyped) && capitalTyped != null) {
//            condition += " and capital_typed = '" + capitalTyped + "'";
//        }
////		String userId = (String)networkInfo.get("userId");
////		if(!"".equals(userId)&&userId!=null) {
////			condition+=" and user_id = '"+userId+"'";
////		}
//        String sql = "select a.*,b.department from t_network_device a left join t_admin_user b on a.user_id = b.user_id " + condition;
//        return BeanUtil.underline2Camel(jdbcTemplate.queryForList(sql));
//    }

    //    //搜索网络设备
    public Page<ItNetworkDevice> searchNetwork(Integer page, Integer size,
                                               String userId, String assetIp, String brandType,
                                               String brandSys, String brandSn, String capitalTyped, String brand, String capitalType) {
        Pageable pageable = PageRequest.of(page - 1, size);
        Page<ItNetworkDevice> list = itNetworkDeviceRepo.searchNetworkDeviceByUser(pageable, userId, assetIp, brandType, brandSys, brandSn, capitalTyped, brand, capitalType);
        List<ItNetworkDevice> flist = list.getContent();
        try {
            for (ItNetworkDevice s : flist) {
                String ss = DateUtil.getStr_yyyyMMdd2(s.getStartTime());
                String ee = DateUtil.getStr_yyyyMMdd2(s.getEndTime());
                s.setStartTimeStr(ss);
                s.setEndTimeStr(ee);
                if (StringUtils.isNotEmpty(s.getUserId())) {
                    User user = userService.findByUserId(s.getUserId());
                    if (user != null) {
                        s.setDepartment(user.getUserDepartment());
                        s.setUserName(user.getName());
                    }
                }
            }
        } catch (Exception e) {
            logger.error("searchNetwork搜索异常", e);
        }
        return list;
    }

    //网络设备导出
    public List<NetworkManageExportFull> queryNetworkFullOutPut() {
        String sql = "select asset_ip,asset_use,brand,brand_type,brand_sys,brand_sn,capital_type,capital_typed,department, " +
                "(select dict_value from t_it_dict b where b.zd_id = a.machine_room) machine_room,machine_cab, " +
                "(select dict_value from t_it_dict c where c.zd_id = a.machine_status) machine_status,machine_sup,start_time,end_time,name  " +
                "from t_it_network_device a " +
                "left join t_user d on a.user_id = d.userid where 1 = 1 ";
        return jdbcTemplate.query(sql, new NetworkRowMapper());
    }

    public List<ItNetworkDevice> searchNetworkSpecial(String nw,boolean isLike) {
        if (isLike){
            return itNetworkDeviceRepo.searchNetworkSpecial(nw);
        }else {
            return itNetworkDeviceRepo.searchNetworkSpecialNotLike(nw);
        }

    }

//    //查询资产标牌页面（无需入参的范例）
//    public List<Map<String, Object>> queryTypeByTypeId(String typeId) {
//        String sql = "select type_id,type_name from t_capital_type limit 1,200";
////		List<Map<String, Object>> queryForList = jdbcTemplate.queryForList(sql, new Object[] {typeId});   测试看是否有数据
//        return BeanUtil.underline2Camel(jdbcTemplate.queryForList(sql, new Object[]{}));
//    }
//
//    ///////////////////////////////////////////////////////////////////////////
//    //多设备删除
//    public void deleteMultNetwork(String[] ids) {
//
//        String sql = "delete from t_network_device where asset_id = ? ";
////		jdbcTemplate.update(sql, new Object[] { ids});
//        List<Object[]> paramList = new ArrayList<>();
//
//        Arrays.asList(ids).forEach((e) -> paramList.add(new Object[]{e}));
//
//        jdbcTemplate.batchUpdate(sql, paramList);
//    }
//
//
//    public Map<String, Object> getInfo(String assetId) {
//        Map<String, Object> conditions = new HashMap<String, Object>();
//        conditions.put("asset_id", assetId);
//        return BeanUtil.underline2Camel(generalDataManager.queryForMap("t_network_device", conditions));
//    }
}
